<template>
  <!-- Questionnaire 问卷调查 -->
  <PageContainer>
    <view class="container">
      <Header title="问卷调查" :is-go-back="true" />
      <view class="warp">
        <view class="desc">
          <view>{{ questionData?.title }}</view>
          <view>{{ questionData?.describe }}</view>
        </view>
        <UniForms ref="form" :modelValue="formData" border label-position="top">
          <template v-for="(item, index) in questionData?.questionList" :key="index">
            <UniFormsItem :label="item.title" :label-width="300" required>
              <!-- 单选、多选文字、图片 -->
              <template v-if="[11, 12, 21, 22].includes(item.questionType)">
                <view class="list">
                  <view
                    v-for="subItem in item.answerList"
                    :class="[11, 21].includes(item.questionType) ? 'item' : 'imgBox'"
                    @click="handleCheck(index, item, subItem, item.questionType)"
                    :key="subItem.answerId"
                  >
                    <img
                      v-if="item.checkedIds?.includes(subItem.answerId)"
                      class="icon"
                      :src="`${
                        [11, 12].includes(item.questionType) ? RadioCheckedImg : CheckBoxCheckedImg
                      }`"
                    />
                    <img
                      v-else
                      class="icon"
                      :src="`${[11, 12].includes(item.questionType) ? RadioImg : CheckBoxImg}`"
                      alt=""
                    />

                    <view v-if="[11, 21].includes(item.questionType)" class="text">
                      {{ subItem.words }}
                    </view>
                    <img v-else class="img" :src="subItem.img" alt="" />
                  </view>
                </view>
              </template>
              <!-- 输入框 -->
              <template v-else-if="item.questionType === 31">
                <UniEasyinput
                  v-model="formData[item.questionId]"
                  :clearSize="20"
                  :clearable="false"
                  :placeholder="`请输入${item.title}`"
                />
              </template>
              <!-- <template v-else-if="item.questionType === 53">
              <UniFilePicker v-model="filesValue" :auto-upload="false" :limit="3" file-mediatype="image"
                file-extname="jpg,png" :list-styles="{ border: false, dividline: false }"
                @select="(e: any) => fileImgSelect(e, 'registerUrl')" @delete="() => fileDetele('registerUrl')">

              </UniFilePicker>
            </template> -->
            </UniFormsItem>
          </template>
        </UniForms>

        <img
          class="feedbackImg"
          src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/floatIcon/feedback-icon.png"
          alt=""
          @click="open('popup')"
        />
        <button class="submitBtn" type="primary" @click="submit('form')">提交问卷</button>

        <uni-popup ref="popup" type="bottom" background-color="#fff">
          <view class="feedback">
            <view class="title">反馈意见</view>
            <UniEasyinput
              type="textarea"
              :clearSize="20"
              v-model="value"
              :clearable="false"
              placeholder="请输入反馈意见"
            />
            <button type="primary" @click="handleFeedbackSubmit('popup')">提交</button>
          </view>
        </uni-popup>
      </view>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  Questionnaire  问卷调查 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import { ref, getCurrentInstance, reactive } from 'vue';
  import Header from '@/components/Header/index.vue';
  import { questionInfo, answerSubmit, feedbackSubmit } from '@/api/questionnaire';
  import {
    type IQuestionResData,
    type IQuestionItem,
    type IAnswerItem,
    type IAnswerSubmitParams,
    type IAnswerItemSubmitParams,
  } from '@/api/questionnaire/types';
  import { uploadImgFiles } from '@/api';
  import { useUserStoreWithOut } from '@/store/modules/user';

  import UniForms from '@/components/Form/uni_modules/uni-forms/uni-forms.vue';
  import UniFormsItem from '@/components/Form/uni_modules/uni-forms-item/uni-forms-item.vue';
  import UniEasyinput from '../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import { onLoad } from '@/router';
  import { isLogin } from '@/utils/is';
  import { Toast } from '@/utils';

  const RadioImg = 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio.png';
  const RadioCheckedImg =
    'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio-checked.png';
  const CheckBoxImg =
    'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/checkbox.png';
  const CheckBoxCheckedImg =
    'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/checkbox-checked.png';

  const _this = getCurrentInstance();
  const useUser = useUserStoreWithOut();
  const value = ref('');
  var questionData = ref<IQuestionResData>({
    questionnaireId: 0, //问卷ID
    title: '', //问卷标题
    describe: '', //问卷描述
    questionList: [], //问题列表
  });

  const formData: any = ref({});
  const id = ref<string>('');
  onLoad<'Questionnaire'>((op) => {
    id.value = op.id;
    isLogin(() => {
      getQuestionInfo();
    });
  });

  const getQuestionInfo = () => {
    questionInfo({ id: id.value }).then((res: IQuestionResData) => {
      questionData.value = res;
      formData.value = res.questionList.reduce((pre: any, cur) => {
        pre[cur.questionId] = cur.questionType === 31 ? undefined : cur.checkedIds || [];
        return pre;
      }, {});
    });
  };

  //单选/多选事件 11, 12单选、21, 22多选
  const handleCheck = (index: number, item: IQuestionItem, subItem: IAnswerItem, type: number) => {
    let checkedIds = item.checkedIds || [];
    let fIndex = checkedIds.findIndex((f) => f === subItem.answerId);
    if ([11, 12].includes(type)) {
      checkedIds = [subItem.answerId];
    } else if ([21, 22].includes(type)) {
      fIndex != -1 ? checkedIds.splice(fIndex, 1) : checkedIds.push(subItem.answerId);
    }
    item.checkedIds = checkedIds;
    formData.value[item.questionId] = checkedIds;
    questionData.value.questionList[index] = item;
  };

  const open = (ref: string) => {
    (_this?.refs[ref] as any).open('bottom');
  };

  const filesValue = ref();

  const fileSize = ref(10);
  function fileImgSelect(e: { tempFilePaths: string[]; tempFiles: TempFile[] }, key: string) {
    let errTitle = '';
    for (let i = 0; i < e.tempFiles.length; i++) {
      const item = e.tempFiles[i];
      if (fileSize.value * 1024 * 1024 < item.size) {
        errTitle = `单张图片大小不能超过：${fileSize.value}MB`;
        continue;
      }
    }
    if (errTitle) return Toast(errTitle);
    uploadImgFiles(e.tempFiles)
      .then((r) => (filesValue.value = r[0].imagePathBig))
      .catch(() => uploadCatch(fileImgSelect, e, key));
  }

  function uploadCatch(callback: Function, e: any, key: string) {
    if (!e.tempFiles) return;
    uni.showModal({
      title: '提示',
      content: '上传失败, 是否立即重新上传',
      confirmText: '是',
      cancelText: '取消',
      success: ({ confirm }) => {
        if (confirm) {
          callback(e, key);
        } else {
          fileDetele(key);
        }
      },
    });
  }

  function fileDetele(key: string) {
    (formData as any)[key] = null;
  }

  //意见反馈提交
  const handleFeedbackSubmit = (ref: string) => {
    if (!value.value) {
      return Toast('请输入反馈意见');
    }
    feedbackSubmit({ questionnaireId: id.value, feedbackContent: value.value }).then((res) => {
      Toast('操作成功');
      (_this?.refs[ref] as any).close();
    });
  };

  //提交问卷
  const submit = (ref: string) => {
    console.log('formData---->', formData.value, filesValue);
    let keys = Object.keys(formData.value);
    for (let k = 0; k < keys.length; k++) {
      if (formData.value[keys[k]] === undefined || !formData.value[keys[k]].length) {
        let item = questionData.value.questionList.find((q) => q.questionId == Number(keys[k]));
        return Toast(`请${(item?.questionType === 31 ? '填写' : '选择') + item?.title}`);
      }
    }

    const answerList: IAnswerItemSubmitParams[] = keys.map((v: string): IAnswerItemSubmitParams => {
      let item = questionData.value.questionList.find((q) => q.questionId == Number(v));
      return {
        questionId: Number(v),
        answerIds: item?.questionType === 31 ? [item.answerList[0].answerId] : formData.value[v],
        words: Array.isArray(formData.value[v]) ? '' : formData.value[v],
      };
    });

    const submitParams: IAnswerSubmitParams = {
      appUserId: useUser.userInfo.userId,
      questionnaireId: id.value,
      answerList,
    };
    answerSubmit(submitParams)
      .then((res) => {
        Toast('提交成功');
      })
      .catch((err: Error) => {
        Toast(err.toString());
      });
  };
</script>

<style lang="scss">
  page {
    height: 100%;
    background-color: #f5f5f5;
  }
</style>

<style lang="scss" scoped>
  .container {
    padding: 30rpx;
    padding-bottom: 0;
    background-color: #fff;

    .warp {
      background: #fff;
      padding-bottom: 200rpx;

      .desc {
        text-align: center;
        margin: 30rpx 0;

        view:first-child {
          font-size: 31rpx;
          color: #333333;
          font-weight: 400;
        }

        view:last-child {
          font-size: 23rpx;
          color: #aaabab;
        }
      }

      .list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        .item {
          display: flex;
          align-items: center;
          width: 50%;
          padding: 15rpx 0;

          .text {
            margin-left: 10rpx;
          }
        }
      }

      .icon {
        width: 30rpx;
        height: 30rpx;
        flex-shrink: 0;
      }

      .imgBox {
        display: flex;
        margin: 10rpx 0;
        width: 50%;

        .icon {
          width: 30rpx;
          height: 30rpx;
        }

        .img {
          width: 250rpx;
          height: 250rpx;
          margin-left: 20rpx;
        }
      }

      ::v-deep {
        .uni-forms-item {
          .uni-forms-item__inner {
            padding: 15rpx 0;
          }
        }

        .uni-forms-item--border {
          padding: 0;
        }

        .uni-forms {
          .is-input-border {
            border: none;
          }
        }
      }

      .feedbackImg {
        position: fixed;
        right: 29rpx;
        bottom: 350rpx;
        width: 108rpx;
        height: 144rpx;
        z-index: 10;
      }

      .submitBtn {
        position: fixed;
        bottom: 87rpx;
        width: 692rpx;
        height: 96rpx;
        line-height: 96rpx;
        border-radius: 48rpx;
        z-index: 10;
      }

      .feedback {
        padding: 0 30rpx;

        .title {
          line-height: 115rpx;
          font-size: 31rpx;
          color: #333333;
          text-align: center;
        }

        ::v-deep {
          .is-input-border {
            background: #f5f5f5;
            border: 2rpx solid #dddddd;
            box-sizing: border-box;
          }
        }

        button {
          height: 96rpx;
          line-height: 96rpx;
          border-radius: 48rpx;
          margin-top: 73rpx;
        }
      }
    }
  }
</style>
